package com.zlp.gateway.service.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * 服务降级
 * @date: 2021/12/27 17:07
 */
@Configuration
public class GatewayConfig {


    @PostConstruct
    public void init() {

        //初始化网关限流规则
        initGatewayRules();
        //自定义限流异常处理器
        initBlockRequestHandler();
    }

    /**
     * 初始化限流规则
     * @date: 2021/12/27 18:02
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        /**
         *  resource：资源名称，可以是网关中的 route 名称或者用户自定义的 API 分组名称。
         *  count：限流阈值
         *  intervalSec：统计时间窗口，单位是秒，默认是 1 秒。
         */
        rules.add(new GatewayFlowRule("order")
                .setCount(1)
                .setIntervalSec(1));
        // 加载网关规则
        GatewayRuleManager.loadRules(rules);

    }

    /**
     * 自定义限流异常处理器
     *
     * @date: 2021/12/27 18:08
     */
    private void initBlockRequestHandler() {

        HashMap<String, String> result = new HashMap<>(2);
        result.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
        result.put("msg", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());

        BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> ServerResponse.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(result));
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);

    }
}
